/**
 * HIPPO Build Script
 *
 * Generate a main.js file by concatenating all the files listed in payload.json
 *
 * usage:
 * $ node scripts/build.js
 */

var fs           = require('fs'),
    path         = require('path'),
    hippo_path   = path.resolve(__dirname, '..', '..'),
    temp_path    = path.resolve(hippo_path, 'main.js.tmp'),
    output_path  = path.resolve(hippo_path, 'main.js'),
    scripts_path = path.resolve(hippo_path, 'scripts'),
    payload_path = path.resolve(scripts_path, 'payload.json'),
    payload      = JSON.parse( fs.readFileSync(payload_path, 'utf8') ),
    code         = '';

// init temp output file
fs.writeFileSync(temp_path, '', 'utf8');

// for each item in the payload.json file...
for (var i = 0; i < payload.length; i++) {
    code = fs.readFileSync( path.resolve(scripts_path, payload[i]), 'utf8' ) + '\n\n';

    // verify the file exists and append its contents to the temp output file
    if (fs.existsSync(temp_path)) {
        fs.appendFileSync(temp_path, code, 'utf8');
    }
}

// overwrite the output file with the temp output file's contents
fs.writeFileSync(
    output_path,
    fs.readFileSync(temp_path, 'utf8'),
    'utf8'
);

// clean up the temp output file
fs.unlinkSync(temp_path);
